import os
import subprocess
from model import DouyinModel
from view import DouyinView

class DouyinController:
    def __init__(self):
        self.model = DouyinModel()
        self.view = DouyinView(self)
        
    def handle_download(self, text):
        try:
            # 提取URL
            self.view.update_status("正在提取分享链接...")
            share_url = self.model.extract_url(text)
            if not share_url:
                self.view.show_error("未找到有效的抖音分享链接")
                return
                
            self.view.update_status(f"提取到的分享链接: {share_url}")
            
            # 获取视频链接
            self.view.update_status("正在获取视频链接...")
            video_url = self.model.get_video_url(share_url)
            if not video_url:
                self.view.show_error("获取视频链接失败")
                return
                
            self.view.update_status(f"视频真实下载链接: {video_url}")
            
            # 下载视频
            self.view.update_status("正在下载视频...")
            filepath = self.model.download_video(video_url, progress_callback=self.view.update_progress)
            
            self.view.update_status(f"视频已下载到: {filepath}")
            self.view.show_success(f"视频下载完成！\n保存位置: {filepath}")
            
        except Exception as e:
            self.view.show_error(str(e))
            self.view.update_status(f"错误: {str(e)}")
            
    def handle_open_folder(self):
        try:
            download_dir = os.path.abspath(self.model.download_dir)
            if os.path.exists(download_dir):
                subprocess.Popen(f'explorer "{download_dir}"')
            else:
                self.view.show_error("下载文件夹不存在")
        except Exception as e:
            self.view.show_error(f"打开文件夹失败: {str(e)}")
            
    def run(self):
        self.view.run()

if __name__ == "__main__":
    app = DouyinController()
    app.run() 